// pages/music/index.js
const ac= wx.getBackgroundAudioManager() 
let lastIndex 

Page({
    onReachBottom: function() {
        console.log('onReachBottom')
        this.request() 
    },
    request(key){ 
        let offset=0
        if(!key){ 
            key=this.data.search
            offset=this.data.songs.length
        }
        if(offset>0 && offset==this.data.songCount)return
		wx.request({
			url: `https://music.163.com/api/search/get/?s=${key}&limit=20&type=1&offset=${offset}`,
            success: r => { 
            
                let change={ songCount: r.data.result.songCount}
                r.data.result.songs.forEach(it=>{ 
                    change[`songs[${offset++}]`]={
						name: it.name,
						id: it.id, 
                        duration: this.formatDuration(it.duration), 
                        album: it.album.name, 
                        
					}
                })
				this.setData(change) 
			},
			fail: e=>{
				console.log(e)
			}
		})
	},

    formatDuration(ms){ 
        let m=parseInt(ms/60000) 
        let s=parseInt(ms/1000%60) 
        return m+":"+(s<10?'0':'')+s 
    },
	play(e){
		
        let index=e.currentTarget.dataset.index 
        let change={ paused: false } 
        if(lastIndex!=null){
			if(index==lastIndex)return 
			change[`songs[${lastIndex}].selected`]=false 
		}
        change[`songs[${index}].selected`]=true 
        lastIndex=index 
        this.setData(change) 
        
        let id=this.data.songs[index].id 
        let mp3=`https://music.163.com/song/media/outer/url?id=${id}.mp3` 
        console.log(mp3)
        ac.src=mp3
        ac.title=this.data.songs[index].name 
		ac.play() 
	},
	pause(e){ 
		if(this.data.paused){
			ac.play() 
		}else{
			ac.pause() 
		}
		this.setData({paused: !this.data.paused})
    },
    search(e){ 
		let search=e.detail.value.trim() 
		this.setData({search, songs:[]})
		this.request(search)
    },
    onUnload(){
        let songMessage=this.data 
        delete songMessage.__webviewId__
        wx.setStorageSync('songMessage', songMessage)
    },
	onLoad(e) {
        ac.onEnded(res=>{ 
			console.log(res) 
			let index=lastIndex+1 
			if(index>=this.data.songs.length)index=0 
			this.play({currentTarget:{dataset:{index}}}) 
			wx.createSelectorQuery().select(`#s${index}`).fields({rect:true, size:true})
			.selectViewport().fields({size:true, scrollOffset:true}).exec(r=>{
				console.log(r)
				let s=r[0], v=r[1]
				if(s.bottom>v.height-20){ 
					wx.pageScrollTo({
						scrollTop: v.scrollTop+(s.bottom-v.height)+20,
						duration: 2000,
					})
			    }else if(s.top<0){
                    wx.pageScrollTo({
						scrollTop: v.scrollTop+s.top,
						duration: 2000,
					})
                }
			})
        })
        let songMessage=wx.getStorageSync('songMessage') 
        console.log(songMessage) 
        if(songMessage){ 
            this.setData(songMessage)
        }
	}
})